<?php
/**
 * Created by PhpStorm.
 * User: Knight
 * Date: 2018/10/23
 * Time: 17:35
 */

namespace app\api\exception;


use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\RouteNotFoundException;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    //需要返回客户端当前请求的URL路径

    /**
     * 设置允许跨域
     */
    public function setHeader(){
        $host_name = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "*";
        return  [
            "Access-Control-Allow-Origin" => $host_name,
            "Access-Control-Allow-Credentials" => 'true',
            "Access-Control-Allow-Headers" => "x-token,x-uid,x-token-check,x-requested-with,content-type,Host,token"
        ];
    }

    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            //如果是自定义异常
            $this->code=$e->code;
            $this->msg=$e->msg;
            $this->errorCode=$e->errorCode;
        }else{
            if(config('app_debug')){
                if($e instanceof HttpException){
                    $this->code=400;
                    $this->msg='地址错误';
                    $this->errorCode=999;
                    $this->recordErrorLog($e);
                }else{
                    return parent::render($e);
                }
            }else{
                $this->code=400;
                $this->msg='服务器内部错误';
                $this->errorCode=999;
                $this->recordErrorLog($e);
            }
        }

//        $url=Request::instance()->url();
        $result=[
            'msg'=>$this->msg,
            'code'=>$this->errorCode,
//            'request_url'=>$url
        ];

        return json($result,$this->code,$this->setHeader());

    }

    /**
     * 异常配置
     * @param Exception $e
     */
    private function recordErrorLog(Exception $e){
        Log::init([
                'type'=>'File',
                'level'=> ['error'],
            ]
        );
        Log::record($e->getMessage(),'error');
    }

}